package com.base.hong.widget

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.base.hong.R

/**
 *
 *Create by Hong on 2023/3/23 13:17.
 *
 */
class CircleCountDownView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val rectF = RectF()
    private var progress = 0f
    private var max = 100f
    private var strokeWidth = 10f
    private var color = Color.BLUE
    private var duration = 10000L
    private var animator: ValueAnimator? = null
    private var listener: OnCountDownFinishListener? = null

    init {
//        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleCountDownView)
//        max = typedArray.getFloat(R.styleable.CircleCountDownView_max, 100f)
//        strokeWidth = typedArray.getDimension(R.styleable.CircleCountDownView_strokeWidth, 10f)
//        color = typedArray.getColor(R.styleable.CircleCountDownView_color, Color.BLUE)
//        duration = typedArray.getInt(R.styleable.CircleCountDownView_duration, 1000).toLong()
//        typedArraypedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.color = color
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = strokeWidth
        rectF.set(strokeWidth / 2, strokeWidth / 2, width - strokeWidth / 2, height - strokeWidth / 2)
        canvas.drawArc(rectF, 120f, progress / max * 300, false, paint)
    }

    fun start() {
        animator?.cancel()
        animator = ValueAnimator.ofFloat(max, 0f).apply {
            duration = this@CircleCountDownView.duration
            interpolator = LinearInterpolator()
            addUpdateListener {
                progress = it.animatedValue as Float
                invalidate()
            }
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    listener?.onCountDownFinish()
                }
            })
            start()
        }
    }
    /**
     * 停止倒计时动画
     */
    fun stop() {
        animator?.cancel()
        animator = null
        progress = 0f
        invalidate()
    }
    fun setOnCountDownFinishListener(listener: OnCountDownFinishListener) {
        this.listener = listener
    }

    interface OnCountDownFinishListener {
        fun onCountDownFinish()
    }
}
